#include "PlayFile.h"

static wxSemaphore	Sema;
static void* Tick(void *T)
{
	static int i=0;
	Sema.Post();
	i++;
	if(i == 250)
	{
		i = 0;
		Sema.Post();
		Sema.Post();
		Sema.Post();
		Sema.Post();
		Sema.Post();
		Sema.Post();
	}
	return NULL;
}

PlayFile::PlayFile(void)
{
	PlayFileDiag myDiag(NULL,&Channels,&SampleFreq,&Resolution,&DigitalMax,&DigitalMin,&DigitalOffset);
	myDiag.ShowModal();
	Instrument::Instrument();
	
	Initialize(Channels,SampleFreq,20); 

	MyName = _("PLAYFILE");

	//Setta la frequenza di visualizzazione
	int tim;
	switch (SampleFreq)
	{
	case 64: 
		tim = 16;
		break;
	case 128: 
		tim = 8;
		break;
	case 256:
		tim = 4;
		break;
	default: 
		tim=4;
		break;
	}
	pTimer = new timer(tim,NULL,&Tick,NULL); //Setta a 4 per 256 8 +er 128
	

}

int PlayFile::ReadData(SampleStruct *pData)
{
	int Dim=0;
	int TempInt=0;
	memset(pData,0,sizeof(pData));
	if (File.Eof()) 
		return 0;
	Dim+=File.Read(&TempInt,sizeof(int));
	pData->Data.DataLen=TempInt;
	Dim+=File.Read(pData->Data.Signal,(unsigned long)(pData->Data.DataLen * sizeof(float)));
	Dim+=File.Read(&pData->Data.AUX,(unsigned long)(sizeof(float)));
	Dim+=File.Read(&pData->Data.Artifacts,(unsigned long)(sizeof(int)));
	Dim+=File.Read(&pData->Algo,(unsigned long)(sizeof(AlgoStruct)));
	Dim+=File.Read(&pData->Events,(unsigned long)(sizeof(EventStruct)));
	return Dim;

}

PlayFile::~PlayFile(void)
{
	if(File.IsOpened())File.Close();
	if(pTimer != NULL)	delete pTimer;
}



void* PlayFile::Entry(void)
{
	bool		SynchOk = false;
	int			Dim;
	int			read;
	SampleStruct	Signal;
	//if(Channels==0) return NULL;
	memset(&Signal,0,sizeof(Signal));
		
	//ch = new char[HowMany];
	read = 0;
	Esci = false;
	while(!Esci)
	{
		if (IsRunning)
		{
			Sema.WaitTimeout(500);
			Dim = ReadData(&Signal);
			if(Dim == 0) 
			{
				if (isLooped)
					File.Seek(0);
				else
				{
					IsRunning = false;
					wxMessageBox(_("End of file reached. Please press stop acquisition!"),_("End of File"));
				}
			}
			else
				PutSample(&Signal);
		}
	}
	
	return NULL;
}
void PlayFile::StartDevice(wxString FileName,wxString FilePath,bool File)
{
	Instrument::StartDevice(FileName,FilePath,File);
	IsRunning	=	true;
	pTimer->start(PERIODIC);
}
void PlayFile::StopDevice(void)
{
	if (IsRunning)
	{
		IsRunning	=	false;
		Instrument::StopDevice();
		pTimer->stop();
	}
}
int PlayFile::OpenPort(const char *PortName, const char *OpenVal2, const char *OpenVal3)
{
	//Open the selected file
	if(!File.IsOpened())
	{
		File.Open(wxString::wxString(PortName,wxConvLibc));
		if(ReadData(&Data)>0)
		{
			File.Seek(0);
		}
		if (wxString::wxString(OpenVal2,wxConvLibc).CompareTo(wxT("1"))==0)
			isLooped = true;
		else
			isLooped = false;		
		return 1;
	}
	else
		return 0;
}